//
//  AppDelegate.m
//  路人侠
//
//  Created by zhangxulong on 16/1/22.
//  Copyright © 2016年 zhangxulong. All rights reserved.
//

#import "AppDelegate.h"
#import "LRXNavigationController.h"
#import "LRXLMeController.h"
#import "LRXHelpMesg.h"
#import "LRXLoginViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AlipaySDK/AlipaySDK.h>
#import "LRXOffline.h"
#import "LRXtipAlerView.h"
#import "LRXSettingController.h"

@interface AppDelegate ()
@property (nonatomic,weak) LRXMenuView * menuController;
@property (nonatomic, strong) Reachability * reachability;

@end


@implementation AppDelegate
- (NSMutableArray *)pushThingArray
{
    if (_pushThingArray == nil) {
        _pushThingArray = [NSMutableArray array];
    }
    return _pushThingArray;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    //获取用户身份
    [self getUserRole];
    //初始化JPushLister 的JPush 的监听
//    [self JPushLister:launchOptions];
    //地图定位的key值
    [AMapLocationServices sharedServices].apiKey = MKKey;
    
    
    
    UIWindow * window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;
    
    //侧边控制器
    LRXMenuView * menuController = [LRXMenuView shareInstance];
    //首页控制器
    LRXHelpMesg * helpMesg = [[LRXHelpMesg alloc]init];
    //设置根控制器
    LRXNavigationController * Nav = [[LRXNavigationController alloc] initWithRootViewController:helpMesg];

    //设置侧边栏
    TWTSideMenuViewController * sideMenuViewController = [[TWTSideMenuViewController alloc]initWithMenuViewController:menuController mainViewController:Nav];
    sideMenuViewController.delegate = self;
   
    sideMenuViewController.shadowColor = [UIColor blackColor];
    sideMenuViewController.edgeOffset = UIOffsetMake(18.0f, 0.0f);
    sideMenuViewController.zoomScale = 0.6634f;
    
    self.menuController = menuController;
    self.window.rootViewController = sideMenuViewController;
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self.window makeKeyAndVisible];
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    // 获得Reachability对象
    self.reachability = [Reachability reachabilityForInternetConnection];
    // 开始监控网络
    [self.reachability startNotifier];
    
    
    //防止主线成 阻塞
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //防止键盘特备慢出来
        UITextField * textField = [[UITextField alloc]init];
        [self.window addSubview:textField];
        [textField becomeFirstResponder];
        [textField resignFirstResponder];
        [textField removeFromSuperview];
    });

    

    return YES;
}

- (void)JPushLister:(NSDictionary * )launchOptions
{
    
    /// Required - 注册 APNs 通知
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        /// 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        /// categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:JPushChannel apsForProduction:JPushIsProduction];
    
    //在前端的时候收到的信息
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    
    
}

//在前端的时候收到的信息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary * userInfo = [notification userInfo];
    NSData * userInfoData = [userInfo[@"content"] dataUsingEncoding:NSUTF8StringEncoding];
    userInfo = [NSJSONSerialization JSONObjectWithData:userInfoData options:0 error:NULL];
    
    NSInteger typeCode = [userInfo[@"type"] integerValue];
    
    NSLog(@"远程推送的数据：%@",userInfo);
    
    //fuck off
    if (typeCode == 1) {
        [LRXOfflineView showOfflineView:@"您的账号在其他设备上登录"];
        [[LRXSettingController alloc]cancelButton];
    }
    //匹配求带请求推送
    else if(typeCode == 2){
        
        LRXHelpMeInfoModel * item = [LRXHelpMeInfoModel helpModelWithDic:userInfo[@"msg"]];
        //代理通知更新数据
        if ([self.appDelegate respondsToSelector:@selector(updateNewPushThing:)]) {
            [self.appDelegate updateNewPushThing:item];
        }
    }
    //all_accepted_waiter_finished 所有订单 都被接了
    else if(typeCode == 4)
    {
        [LRXOfflineView showOfflineView:@"您的帮带任务已完成"];
        self.userRole =USERNORMALTYPE;
    }
    //可以开始推送了
    else if(typeCode == 5)
    {
        
    }
    //帮带者所接订单集合已经为空
    else if(typeCode == 6)
    {
        self.userRole = USERNORMALTYPE;
    }
    //订单长时间未被接受，加价提醒推送
    else if(typeCode == 7)
    {
        //LRXTipAlerView * pp = [LRXTipAlerView tipAlerView];
        //[[UIApplication sharedApplication].keyWindow addSubview:pp];
    }
    
    
}

//希望用户知道 alerView
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"alerView %s %@",__func__,userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"%s",__func__);
        }];
    }
    return YES;
}
//每一次打开和关闭的时候 进行判断 进行 状态栏 变换
- (UIStatusBarStyle)sideMenuViewController:(TWTSideMenuViewController *)sideMenuViewController statusBarStyleForViewController:(UIViewController *)viewController
{
    if (viewController == self.menuController) {
        return UIStatusBarStyleLightContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}

//获取身份
- (void)getUserRole
{
    self.userRole = USEROFFLINETYPE;
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    [manger GET:getUserRoleUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"data"][@"status_code"] isEqualToString:@"1"]) {
            self.userRole = [responseObject[@"data"][@"role"] integerValue];
        }
        else if([responseObject[@"data"][@"status_code"] isEqualToString:@"2"])
        {
            self.userRole = USEROFFLINETYPE;
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [LRXOfflineView showOfflineView:@"您的网络不给力，请稍后再试"];
        });
        
    }];
}
- (void)networkStateChange
{
    //wifi 状态
    if([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable)
    {
        NSLog(@"wifi状态");
        
    }
    //本地网络 状态
    else if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable)
    {
        NSLog(@"本地网络状态");
        
    }
    else
    {
        NSLog(@"没有网络");
        [LRXOfflineView showOfflineView:@"您的网络不给力，请稍后再试"];
        
    }
}

- (void)dealloc
{
    [self.reachability stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
